import * as vscode from 'vscode';
import * as path from 'path';
import { MavenUtils } from '../mavenUtils';

/**
 * 依赖分析视图的树节点
 */
export class DependencyItem extends vscode.TreeItem {
    constructor(
        public readonly artifactId: string,
        public readonly groupId: string,
        public readonly version: string,
        public readonly scope: string | undefined,
        public readonly depth: number,
        public readonly hasConflicts: boolean,
        public readonly pomPath: string | undefined
    ) {
        super(`${artifactId} (${version})`, vscode.TreeItemCollapsibleState.None);
        
        this.description = `${groupId} - ${scope || 'compile'}`;
        this.tooltip = `${groupId}:${artifactId}:${version} [${scope || 'compile'}]`;
        
        // 为冲突依赖设置不同图标和颜色
        if (hasConflicts) {
            this.iconPath = new vscode.ThemeIcon('warning');
            this.contextValue = 'conflictDependency';
        } else {
            this.iconPath = new vscode.ThemeIcon('package');
            this.contextValue = 'dependency';
        }
    }
}

/**
 * 依赖分析视图的数据提供者
 */
export class DependencyAnalyzerProvider implements vscode.TreeDataProvider<DependencyItem> {
    private _onDidChangeTreeData = new vscode.EventEmitter<DependencyItem | undefined>();
    readonly onDidChangeTreeData = this._onDidChangeTreeData.event;
    
    private mavenUtils: MavenUtils;
    private dependencies: DependencyItem[] = [];
    private currentPom: string | undefined;
    
    constructor() {
        this.mavenUtils = new MavenUtils();
    }
    
    /**
     * 刷新视图
     */
    public refresh(): void {
        this._onDidChangeTreeData.fire(undefined);
    }
    
    /**
     * 设置当前分析的POM文件
     */
    public async setPomFile(pomPath: string): Promise<void> {
        this.currentPom = pomPath;
        await this.analyzeDependencies();
        this.refresh();
    }
    
    /**
     * 分析依赖并更新视图
     */
    private async analyzeDependencies(): Promise<void> {
        if (!this.currentPom) {
            this.dependencies = [];
            return;
        }
        
        try {
            // 执行Maven命令获取依赖树
            const output = await this.mavenUtils.executeMavenCommand(
                path.dirname(this.currentPom),
                'dependency:tree'
            );
            
            // 解析依赖数据
            this.dependencies = this.parseDependencyOutput(output, this.currentPom);
        } catch (error) {
            vscode.window.showErrorMessage(`分析依赖失败: ${error}`);
            this.dependencies = [];
        }
    }
    
    /**
     * 解析Maven dependency:tree命令的输出
     */
    private parseDependencyOutput(output: string, pomPath: string): DependencyItem[] {
        const dependencies: DependencyItem[] = [];
        const lines = output.split('\n');
        
        // 跟踪已经看到的依赖项，用于冲突检测
        const seenDependencies = new Map<string, string[]>(); // key: groupId:artifactId, value: [versions]
        
        for (const line of lines) {
            // 跳过无关行
            if (!line.includes('+- ') && !line.includes('\\- ')) {
                continue;
            }
            
            // 计算深度
            const depth = (line.search(/[+\\]/) / 3);
            
            // 解析依赖信息
            const match = line.match(/([\w\.-]+):([\w\.-]+):([\w\.-]+)(?::([\w\.-]+))?(?::([\w\.-]+))?/);
            if (!match) {
                continue;
            }
            
            const [, groupId, artifactId, type, classifier, version] = match;
            
            // 确定作用域
            let scope = 'compile';
            if (line.includes('(test)')) {
                scope = 'test';
            } else if (line.includes('(provided)')) {
                scope = 'provided';
            } else if (line.includes('(runtime)')) {
                scope = 'runtime';
            } else if (line.includes('(system)')) {
                scope = 'system';
            }
            
            // 记录依赖版本
            const key = `${groupId}:${artifactId}`;
            if (!seenDependencies.has(key)) {
                seenDependencies.set(key, []);
            }
            seenDependencies.get(key)!.push(version || '');
            
            // 检测是否有冲突
            const hasConflict = seenDependencies.get(key)!.length > 1;
            
            dependencies.push(new DependencyItem(
                artifactId,
                groupId,
                version || '',
                scope,
                depth,
                hasConflict,
                pomPath
            ));
        }
        
        return dependencies;
    }
    
    /**
     * 获取TreeItem
     */
    public getTreeItem(element: DependencyItem): vscode.TreeItem {
        return element;
    }
    
    /**
     * 获取子项
     */
    public getChildren(element?: DependencyItem): DependencyItem[] {
        if (!element) {
            // 根级别 - 返回所有依赖
            return this.dependencies;
        }
        
        // 依赖项没有子项
        return [];
    }
    
    /**
     * 仅显示冲突依赖
     */
    public showConflictsOnly(): void {
        this.dependencies = this.dependencies.filter(d => d.hasConflicts);
        this.refresh();
    }
    
    /**
     * 显示所有依赖
     */
    public showAllDependencies(): void {
        this.analyzeDependencies();
        this.refresh();
    }
}
